import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Modal, Form, Input, Select, DatePicker, message } from 'antd'
import PropTypes from 'prop-types'
import moment from 'moment'
import TimePicker from '../TimePicker/Index'
import { awaitWrap } from '@js/tool'
const { Item } = Form
const { Option } = Select
const { TextArea } = Input
class OperateModal extends Component {
  state = {
    caseList: [],
    roomList: [],
    loading: false
  }

  formRef = React.createRef()

  // 获取案件列表
  getCaseList (v) {
    this.setState({ loading: true })
    this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'caseno_desc', o: 'like', v: `%${v}%` }])
    }).then(res => {
      this.setState({ loading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        caseList: res.data.list
      })
    }).catch(() => this.setState({ loading: false }))
  }

  async getRoomList () {
    const [e, d] = await awaitWrap(this.$get('/api/xapc/hearingroom/getHearingroomCloud'))
    if (e === null && d !== null) {
      this.setState({
        roomList: d.data
      })
    }
  }

  selectCase (v) {
    let c = null
    const list = this.state.caseList
    for (let i = 0; i < list.length; i++) {
      if (list[i].caseno_desc === v) {
        c = list[i]
        break
      }
    }
    if (c) {
      this.formRef.current.setFieldsValue({
        caseid: c.id
      })
    }
  }

  // 格式化数据
  initData () {
    const { caseid, caseno_desc: d, begin_datetime: b, end_datetime: e, remark, use } = this.props.data
    const dateStr = b ? moment(b * 1000).format('YYYY-MM-DD') : ''
    const data = {
      caseid: caseid || '',
      caseno_desc: d || undefined,
      date: dateStr ? moment(dateStr) : undefined,
      begintime: b && dateStr ? moment(`${dateStr} ${moment(b * 1000).format('HH:mm')}`) : undefined,
      endtime: e && dateStr ? moment(`${dateStr} ${moment(e * 1000).format('HH:mm')}`) : undefined,
      remark: remark || undefined,
      use: use || undefined
    }
    if (!this.formRef.current) {
      setTimeout(() => {
        this.initData()
      }, 100)
    } else {
      this.formRef.current.setFieldsValue(data)
    }
  }

  // 获取禁用日期
  getDisabledDate (c) {
    const today = moment(moment().format('YYYY-MM-DD'))
    return c < today
  }

  onFinish (d) {
    let { date, begintime, endtime } = d
    date = date.format('YYYY-MM-DD')
    d.begin_datetime = moment(`${date} ${begintime.format('HH:mm')}`)
    d.end_datetime = moment(`${date} ${endtime.format('HH:mm')}`)
    delete d.date
    delete d.begintime
    delete d.endtime
    this.props.onChange(d)
  }

  // 获取禁用的小时数
  getDisabledHour () {
    const rs = []
    let i = 0
    while (i <= 24) {
      if (i < 8 || i > 23) {
        rs.push(i)
      }
      i++
    }
    return rs
  }

  // 获取不可选的分钟数
  getDisabledMinute () {
    const rs = []
    let i = 0
    while (i < 60) {
      if (i % 15 !== 0) {
        rs.push(i)
      }
      i++
    }
    return rs
  }

  componentDidUpdate (prev) {
    const { visible, data } = this.props
    if (!prev.visible && visible) {
      this.initData()
      this.getCaseList(data.caseno_desc || '')
    }
  }

  componentDidMount () {
    this.getRoomList()
  }

  render () {
    const { id } = this.props.data
    return (
      <Modal
        title={id ? '修改视频庭审' : '新增视频庭审'}
        open={this.props.visible}
        onOk={() => this.formRef.current.submit()}
        onCancel={() => this.props.hide()}
      >
        <Form ref={this.formRef} labelCol={{ flex: '88px' }} onFinish={d => this.onFinish(d)}>
          <Item noStyle name='caseid'><span /></Item>
          <Item label='案号' name='caseno_desc' rules={[{ required: true, message: '案号不能为空' }]}>
            <Select showSearch placeholder='选择案号' onSearch={v => this.getCaseList(v)} onChange={v => this.selectCase(v)}>
              {this.state.caseList.map(li => <Option key={li.id} value={li.caseno_desc}>{li.caseno_desc}</Option>)}
            </Select>
          </Item>
          <Item label='虚拟庭室' name='hearingroomid' rules={[{ required: true, message: '虚拟庭室不能为空' }]}>
            <Select placeholder='请选择'>
              {this.state.roomList.map(li => <Option key={li.id} value={li.id}>{li.name}</Option>)}
            </Select>
          </Item>
          <Item label='用途' name='use' rules={[{ required: true, message: '用途不能为空' }]}>
            <Select placeholder='请选择用途'>
              <Option value='开庭'>开庭</Option>
              <Option value='合议'>合议</Option>
              <Option value='调解'>调解</Option>
            </Select>
          </Item>
          <Item label='开庭日期' name='date' rules={[{ required: true, message: '开庭不能为空' }]}>
            <DatePicker style={{ width: '100%' }} disabledDate={c => this.getDisabledDate(c)} />
          </Item>
          <Item label='开始时间' name='begintime' rules={[{ required: true, message: '开始时间不能为空' }]}>
            <TimePicker format='HH:mm' disabledHours={() => this.getDisabledHour()} disabledMinutes={() => this.getDisabledMinute()} />
          </Item>
          <Item label='结束时间' name='endtime' rules={[{ required: true, message: '结束时间不能为空' }]}>
            <TimePicker format='HH:mm' disabledHours={() => this.getDisabledHour()} disabledMinutes={() => this.getDisabledMinute()} />
          </Item>
          <Item label='备注' name='remark'>
            <TextArea rows={3} placeholder='请输入备注' />
          </Item>
        </Form>
      </Modal>
    )
  }
}

OperateModal.proptypes = {
  visible: PropTypes.bool,
  data: PropTypes.object,
  hide: PropTypes.func,
  onChange: PropTypes.func
}

OperateModal.defaultProps = {
  visible: false,
  data: {},
  hide: () => {},
  onChange: () => {}
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(OperateModal)
